import { AppDataSource } from "../data-source";
import { NextFunction, Request, Response } from "express";
import { Role } from "../entity/Role";

export class RoleController {
  private roleRespository = AppDataSource.getRepository(Role);

  async save(request: Request, response: Response, next: NextFunction) {
    const { name } = request.body;
    const role = new Role();
    role.name = name;
    const savedRole = await this.roleRespository.save(role);
    response.json(savedRole);
  }

  async one(request: Request, response: Response, next: NextFunction) {
    const { id } = request.params;
    const role = await this.roleRespository.findOne({
      where: { id },
      relations: ["users"],
    });
    response.json(role);
  }

  async all(request: Request, response: Response, next: NextFunction) {
    const roles = await this.roleRespository.find();
    response.json(roles);
  }
}
